package com.zjm.creational.singleton.type03;

/**
 * 懒汉式（线程不安全）
 */
public class SingletonTest03 {
    public static void main(String[] args) {
        // System.out.println(Singleton.getInstance());
        // System.out.println(Singleton.getInstance());
        // System.out.println(Singleton.getInstance());
        // System.out.println(Singleton.getInstance());

        // 模拟10个线程并发获取单例对象
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 获取到的实例：" + Singleton.getInstance());
            }, "线程-" + i).start();
        }
    }
}

class Singleton {
    private static Singleton INSTANCE;

    // 构造器私有化
    private Singleton() {
    }

    // 提供公共的静态方法，返回实例对象
    public static Singleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton();
        }
        return INSTANCE;
    }
}
